package top.littlematch.mongo.controller;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.littlematch.mongo.model.Hello;

import javax.annotation.Resource;

/**
 * @ Description：${description}
 * @ Author     ：Match
 * @ Date       ：下午 18:05 2018/12/5 0005
 * @Version: $version$
 */
@RestController
@RequestMapping("hello")
public class HelloController {
    /**
     * 使用mongoTemplate去操作mongodb
     */
    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * mongodb表名
     */
    final static String HELLO = "HELLO";

    /**
     * 获取数据
     *
     * @return
     */
    @RequestMapping("/insert")
    public void insertHello(@RequestParam(name = "name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        mongoTemplate.insert(hello, HELLO);
    }

    /**
     * 获取数据
     *
     * @return
     */
    @RequestMapping("/get")
    public Hello getHello(@RequestParam(name = "name") String name) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, Hello.class, HELLO);
    }

    /**
     * 更新数据
     *
     * @return
     */
    @RequestMapping("/update")
    public void updateHello(@RequestParam(name = "name") String name) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        Hello hello = new Hello();
        hello.setName(name);
        Update update = new Update();
        update.set("name", name);
        mongoTemplate.updateFirst(query, update, Hello.class, HELLO);
    }

    /**
     * 删除数据
     *
     * @return
     */
    @RequestMapping("/delete")
    public void deleteHello(@RequestParam(name = "name") String name) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        mongoTemplate.remove(query, Hello.class, HELLO);
    }

}
